import os
from flask import Flask
from .libs.jsonify import CustomJSONEncoder
from .libs.logs import register_logging
from .config import config
from .redis import rd

# 获得项目根目录
basedir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))

def create_app(env='dev'):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)

    # 日期 json 格式化的时候有问题，处理一下
    app.json_encoder = CustomJSONEncoder
    
    app.config.from_object(config[env])
    # redis 初始化，连接池最大 10 个
    rd.init_app(app, max_connections = 10)

    # 数据库连接
    from .models.database import db
    db.init_app(app)

    # 蓝图导入，模块化组织
    from .bluprint import reg_blueprint
    reg_blueprint(app)
    # 注册日志
    register_logging(app, basedir)

    return app


